package com.study.qqserve.service;

import com.study.qqcommon.Message;
import com.study.qqcommon.MessageType;
import com.study.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

//监听 9999 端口，等待客户端连接，并保持通讯
public class QQServer {
    private ServerSocket server = null;

    //用户集合 ConcurrentHashMap 线程安全 HashMap 线程不安全
    public static ConcurrentHashMap<String,User> validUsers = new ConcurrentHashMap<String,User>();

    static {
        validUsers.put("100", new User("100", "123"));
        validUsers.put("200", new User("200", "123"));
        validUsers.put("300", new User("300", "123"));
        validUsers.put("400", new User("400", "123"));
        validUsers.put("500", new User("500", "123"));
        validUsers.put("至尊宝", new User("至尊宝", "123"));
        validUsers.put("罗", new User("罗", "123"));
        validUsers.put("八戒", new User("八戒", "123"));
    }

    //验证用户信息 是否存在
    public static boolean checkUser(User user) {
        User validUser = validUsers.get(user.getUserId());
        if(validUser == null) {
            System.out.println("User " + user.getUserId() + " not exist");
            return false;
        }
        if(!validUser.getPassword().equals(user.getPassword())){
            System.out.println("User " + user.getUserId() + " password is wrong");
            return false;
        }
        return true;
    }

    public QQServer() {
        try {
            System.out.println("QQServer is running prot：9999 waiting for client connection");
            //启动服务器消息推送线程
            new Thread(new SendNewsToAllService()).start();

            server = new ServerSocket(9999);
            while (true) {
                Socket socket = server.accept();
                System.out.println("A client is connected");
                //读取客户端发来的消息
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                User user = (User) ois.readObject();
                Message message = new Message();


                //验证用户信息
                if(checkUser(user)) {
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    //将验证结果返回给客户端
                    oos.writeObject(message);
                    //创建一个线程，保持和客户端通讯
                    ServerContentThread serverContentThread = new ServerContentThread(socket, user.getUserId());
                    serverContentThread.start();
                    MangerClientThreads.addClientThread(user.getUserId(), serverContentThread);
                    System.out.println("User " + user.getUserId() + " login succeed");
                    //获取该用户离线消息，如果有离线消息才去读取和发送离线消息
                    List<Message> historyMessages = OfflineMessagesService.getHistoryMessages(user.getUserId());
                    if(!historyMessages.isEmpty()) {
                        //发送离线消息
                        OfflineMessagesService.sendOfflineMessage(user.getUserId());
                    }
                } else {
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    socket.close();
                    System.out.println("User " + user.getUserId() + " login failed");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //如果服务端退出循环，关闭服务端
            try {
                if (server != null) {
                    server.close();
                    System.out.println("Server is closed");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
